import pygame
import random

# 初始化 Pygame
pygame.init()

# 定义常量
WIDTH = 800
HEIGHT = 600
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
PLAYER_WIDTH = 50
PLAYER_HEIGHT = 50
OBSTACLE_WIDTH = 30
OBSTACLE_HEIGHT = 30
PLAYER_SPEED = 5
OBSTACLE_SPEED = 3
JUMP_POWER = 12
GRAVITY = 0.5

# 创建游戏窗口
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("跑酷游戏")

# 玩家类
class Player:
    def __init__(self):
        self.x = 50
        self.y = HEIGHT - PLAYER_HEIGHT
        self.vel_y = 0
        self.is_jumping = False

    def jump(self):
        if not self.is_jumping:
            self.vel_y = -JUMP_POWER
            self.is_jumping = True

    def move(self):
        keys = pygame.key.get_pressed()
        if keys[pygame.K_UP]:
            self.jump()

        if self.is_jumping:
            self.vel_y += GRAVITY
            self.y += self.vel_y
            if self.y >= HEIGHT - PLAYER_HEIGHT:
                self.y = HEIGHT - PLAYER_HEIGHT
                self.vel_y = 0
                self.is_jumping = False

    def draw(self):
        pygame.draw.rect(screen, WHITE, (self.x, self.y, PLAYER_WIDTH, PLAYER_HEIGHT))

# 障碍物类
class Obstacle:
    def __init__(self):
        self.x = WIDTH
        self.y = HEIGHT - OBSTACLE_HEIGHT

    def move(self):
        self.x -= OBSTACLE_SPEED

    def draw(self):
        pygame.draw.rect(screen, WHITE, (self.x, self.y, OBSTACLE_WIDTH, OBSTACLE_HEIGHT))

    def is_off_screen(self):
        return self.x + OBSTACLE_WIDTH < 0

    def collides_with(self, player):
        return (
            player.x < self.x + OBSTACLE_WIDTH and
            player.x + PLAYER_WIDTH > self.x and
            player.y < self.y + OBSTACLE_HEIGHT and
            player.y + PLAYER_HEIGHT > self.y
        )

# 创建玩家和障碍物列表
player = Player()
obstacles = []
score = 0
font = pygame.font.Font(None, 36)

# 游戏主循环
clock = pygame.time.Clock()
running = True
while running:
    screen.fill(BLACK)

    # 处理事件
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

    # 玩家移动
    player.move()

    # 随机生成障碍物
    if random.randint(1, 100) < 2:
        obstacles.append(Obstacle())

    # 移动和绘制障碍物
    for obstacle in obstacles[:]:
        obstacle.move()
        obstacle.draw()
        if obstacle.is_off_screen():
            obstacles.remove(obstacle)
            score += 1
        elif obstacle.collides_with(player):
            print(f"游戏结束，你的得分是: {score}")
            running = False

    # 绘制玩家
    player.draw()

    # 显示得分
    score_text = font.render(f"得分: {score}", True, WHITE)
    screen.blit(score_text, (10, 10))

    # 更新显示
    pygame.display.flip()
    clock.tick(60)

# 退出游戏
pygame.quit()